using Newtonsoft.Json;
using Quartz;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.ScheduleJob.SPI;
using T.ServiceComponent.Kernel.Service;

namespace T.FAS.Runtime.ScheduleJob.Engine
{
    public class BasicScheduleJobExcutor : IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            var data = context.MergedJobDataMap;

            try
            {
                var jContextContent = data.GetString(ScheduleJobRTPConst.DefaultJobContextDataKey);
                var jContext = JsonConvert.DeserializeObject<ScheduleJobExecContext>(jContextContent);
                if (jContext == null)
                    throw new FasException(ScheduleJobRTPExceptionCode.ScheduleJobRTPNullArgument, CommonStringClassEngine.BasicScheduleJobExcutor_Execute);

                var engine = new ScheduleJobExecuteEngine();
                AppendMonitorInfo(jContext);
                return Task.Factory.StartNew(() =>
                {
                    engine.Execute(jContext);
                });
            }
            catch (Exception ex)
            {
                throw new FasException(ScheduleJobRTPExceptionCode.ScheduleJobExecuteError,string.Format(CommonStringClassEngine.BasicScheduleJobExcutor_Execute1,ex.ToString()));
            }
        }
        private void AppendMonitorInfo(ScheduleJobExecContext context)
        {
            var requestID = RpcContext.Current.RequestID;
            if (string.IsNullOrEmpty(requestID))
                requestID = Guid.NewGuid().ToString();
            context.AddData("RequestID", requestID);
            var rpcID = RpcContext.Current.RpcID;
            if (string.IsNullOrEmpty(rpcID))
                rpcID = Guid.NewGuid().ToString();
            context.AddData("RpcID", rpcID);
        }
    }
}
